<?php

/**
 * Description of Application_Model_Csv
 *
 * @author Jean Brito
 */
abstract class Application_Model_Csv extends Application_Model_Fix {

	const DIR='data/csv';
	const EXTENSAO='.csv';

	static public function index($model, $filter = null, $start = null, $limit = null, $sort = null) {
		self::read($model);
		return parent::index($model, $filter, $start, $limit, $sort);
	}

	static public function post($model,$params) {
		self::read($model);
		$result=parent::post($model,$params);
		self::write($model);
		return $result;
	}

	static public function delete($model,$id) {
		self::read($model);
		$result=parent::delete($model,$id);
		self::write($model);
		return $result;
	}

	static public function put($model,$id, $params) {
		self::read($model);
		$result=parent::put($model,$id,$params);
		self::write($model);
		return $result;
	}

	static public function read($model){
		$data=array();
		if(file_exists($model->getFileName())){
			$rows=explode("\r\n",file_get_contents($model->getFileName()));
			$headers=array();
			foreach($rows as $i=>$r)if($i==0){
				$row=explode(";",$r);$loadRow=array();$f=0;
				foreach($row as $pos=>$field){
					$header[$pos]=$field;
				}
			}else{
				if(strlen($r)){
					$row=explode(";",$r);$loadRow=array();$f=0;
					foreach($row as $pos=>$value){
						if($header[$pos]!="")
							$loadRow[$header[$pos]]=$value;
					}
					$data[]=$loadRow;
				}
			}
		}
		$model->setData($data);
		return $data;
	}

	static public function write($model){

		$fd=explode('/',trim($model->getFileName(),"/"));
		$file="./";
		foreach($fd as $d=>$dir){
			$file.=$dir;
			if(!is_dir($file)&&$d<(count($fd)-1)){
				mkdir($file);
			}
			$file.="/";
		}

		$fo=fopen($model->getFileName(),'w');

		$header="";
		foreach($model->getFields() as $fld=>$field)
			$header.=$field['name'].";";
		fwrite($fo,$header."\r\n");

		foreach($model->getData() as $row){
			$line="";
			foreach($model->getFields() as $fld=>$field){
				$line.=(isset($row[$field['name']])?$row[$field['name']]:'').";";
			}
			fwrite($fo,$line."\r\n");
		}
		fclose($fo);
	}


}
